#include "controller.h"
#include "workthread.h"
#include <qDebug>
Controller::Controller(QObject *parent) : QObject{parent} {

  auto *worker = new workThread();

  // 调用 moveToThread 将该任务交给 workThread
  worker->moveToThread(&m_workerThread);

  // operate 信号发射后启动线程工作
  connect(this, SIGNAL(operate(const int)), worker, SLOT(doWork(int)));

  // 该线程结束时销毁
  connect(&m_workerThread, &QThread::finished, worker, &QObject::deleteLater);

  // 线程结束后发送信号，对结果进行处理
  connect(worker, SIGNAL(resultReady(int)), this, SLOT(handleResults(int)));

  // 启动线程
  m_workerThread.start();

  // 发射信号，开始执行
  qDebug() << "emit the signal to execute!";
  qDebug() << "\tCurrent thread ID:" << QThread::currentThreadId() << '\n';

  emit operate(0);
  //  initTimer();
}

Controller::~Controller() {
  m_workerThread.quit();
  m_workerThread.wait();
}

void Controller::initTimer() {

  m_timer.setInterval(100);
  connect(&m_timer, SIGNAL(timeout()), this, SLOT(timeout()));
  m_timer.moveToThread(&m_timeThread);
  m_timer.start();
}

void Controller::handleResults(int result) {
  qDebug() << "receive the resultReady signal";
  qDebug() << "\tCurrent thread ID: " << QThread::currentThreadId() << '\n';
  qDebug() << "\tThe last result is: " << result;
}

void Controller::timeout() {
  qDebug() << "\time out thread ID: " << QThread::currentThreadId() << '\n';
}
